import {
    _decorator,
    animation,
    Animation,
    AnimationClip,
    Component,
    Node,
    resources,
    Sprite,
    SpriteFrame,
    UITransform,
} from "cc";
import { TILE_HEIGHT, TILE_WIDTH } from "../Scene/TileManager";
import { CONTROLLER_ENUM, DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_TYPE, PARAMS_NAME_ENUM } from "../../Enums";
import DataManager from "../../Runtime/DataManager";
import { WoodenSkeletonStateMachine } from "./WoodenSkeletonStateMachine";
import EventManager from "../../Runtime/EventManager";
import { EnemyManager } from "../../Base/EnemyManager";
import { IEntity } from "../../Levels";
const { ccclass, property } = _decorator;

@ccclass("WoodenSkeletonManager")
export class WoodenSkeletonManager extends EnemyManager {

    async init(params: IEntity) {
        this.fsm = this.addComponent(WoodenSkeletonStateMachine);
        await this.fsm.init();

        super.init(params);
        EventManager.Instance.on(EVENT_TYPE.PLAYER_MOVE_END, this.tryToAttach, this);
    }

    protected onDestroy(): void {
        super.onDestroy();
        EventManager.Instance.off(EVENT_TYPE.PLAYER_MOVE_END, this.tryToAttach);
    }

    update() {
        super.update();
    }

    tryToAttach() {
        if (!DataManager.Instance.player) {
            return
        }

        if (this.state === ENTITY_STATE_ENUM.DEATH) {
            return;
        }

        if (DataManager.Instance.player.state === ENTITY_STATE_ENUM.DEATH || DataManager.Instance.player.state === ENTITY_STATE_ENUM.AIR_DEATH) {
            return;
        }

        const { x: playerX, y: playerY } = DataManager.Instance.player;
        if (
            playerX === this.x && Math.abs(playerY - this.y) <= 1 ||
            playerY === this.y && Math.abs(playerX - this.x) <= 1
        ) {
            this.state = ENTITY_STATE_ENUM.ATTACH;
            EventManager.Instance.emit(EVENT_TYPE.ATTACH_PLAYER, ENTITY_STATE_ENUM.DEATH);
        } else {
            this.state = ENTITY_STATE_ENUM.IDLE;
        }
    }
}
